const DB = require('../init');
const {Sequelize,Op} = require('sequelize');
const fw = require('../../core/framework');

module.exports = {
    async create(data) {
        DB.Device.sync();
        return await DB.Device.create(data);
    },
    async delete(data) {
        return await DB.Device.destroy({
            where: {
                id: data.id
            }
        });
    },
    async update(data) {
        return await DB.Device.update(data, {
            where: {
                id: data.id
            }
        });
    },
    async read(data){
        return await DB.Device.findOne({where:data});
    },
    async searchAllToAI(){
        return await DB.Device.findAll({
            where:{
                eigen_value:{
                    [Op.not]:null
                }
            },
            attributes: {
                exclude: ['createdAt', 'updatedAt','remark','eigen_value'],
                include:[
                    ['eigen_value','device_eigen_value']
                ]
            }
        });
    },
    async search(data) {
        let query = {
            attributes: {
                exclude: ['createdAt', 'updatedAt'],
                include: [
                    [Sequelize.fn('date_format', Sequelize.col('created_at'), '%Y-%m-%d %H:%i:%s'), 'createtime'],
                    [Sequelize.fn('date_format', Sequelize.col('updated_at'), '%Y-%m-%d %H:%i:%s'), 'updatetime'],
                ]
            }
        };
        if(data){
            query.where = data;
        }
        return await DB.Device.findAll(query);
    },
    async getDataById(data){
        return await DB.Device.findAll({
            where: data
        });
    },
    async searchAll(data){
        let currentPage = data.index || 0;
        let count = data.size || 10;
        let offset = currentPage * count;
        let query = {
            offset:offset,
            limit: parseInt(count),
            order: [
                ['created_at', 'desc'] // 按时间倒序，最新创建的在最上面。  正序是asc
            ],
            where:{
                merchant_id:data.merchant_id
            },
            attributes: {
                exclude: ['createdAt', 'updatedAt'],
                include: [
                    [Sequelize.fn('date_format', Sequelize.col('created_at'), '%Y-%m-%d %H:%i:%s'), 'createtime'],
                    [Sequelize.fn('date_format', Sequelize.col('updated_at'), '%Y-%m-%d %H:%i:%s'), 'updatetime'],
                ]
            },
        };
        if(data.name){
            query.where.name = {
                [Op.like]:'%' + data.name + '%'
            }
        }
        return await DB.Device.findAndCountAll(query).then(deviceRes => {
            deviceRes = JSON.parse(JSON.stringify(deviceRes));
            const keys =  Object.keys(deviceRes.rows);
            const queryAlarmContactGroupDevice = keys.map((d) => {
                return DB.AlarmContactGroupDevice.findAll({
                    where:{
                        device_id:deviceRes.rows[d].id
                    },
                    // group:'alarm_contact_group_id',
                    attributes:{
                        exclude: ['createdAt', 'updatedAt','merchant_id','id']
                    }
                })
            });
            return Promise.all(queryAlarmContactGroupDevice).then(AlarmContactGroupDeviceRes =>{
                deviceRes.rows.forEach((device,index)=>{
                    deviceRes.rows[index]['alarm_contact_group_id'] = AlarmContactGroupDeviceRes[index];
                });
                return fw.genPageData(data,deviceRes);
            });
        });
    }
};
